package com.ck.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.ck.common.constant.AjaxResult;
import com.ck.common.constant.Constants;
import com.ck.common.utils.ip.ServletUtils;
import com.ck.common.utils.txt.StringUtils;
import com.ck.common.vo.LoginUserVo;
import com.ck.framework.manager.AsyncManager;
import com.ck.framework.manager.factory.AsyncFactory;
import com.ck.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author changk
 * @date 2024/11/13 9:29
 * desc: 自定义退出处理类
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        LoginUserVo loginUser = tokenService.getLoginUser(httpServletRequest);
        if (StringUtils.isNotNull(loginUser)){
            //删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            //记录退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUsername(), Constants.LOGOUT,"退出成功"));
        }
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(AjaxResult.success("退出成功")));
    }
}
